<template>
  <div style="margin: 0 -24px">
    <q-scroll-area style="overflow: hidden;padding: 0 24px" class="full-height" ref="scrollTargetRef" :thumb-style="thumbStyle">
      <q-infinite-scroll :offset="100" :scroll-target="$refs.scrollTargetRef"  ref="scrollTarget">
        <div class="row flex">
          <div class="col-lg-3 col-md-6 col-sm-12">
            <div class="wrapper md-margin l-margin">
              <GatewayDetail :box-id="boxId" :detailInfo="detailInfo" :isOnline="isOnline" />
            </div>
          </div>
          <div class="col-lg-3 col-md-6 col-sm-12">
            <div class="wrapper md-margin">
              <LanParams :lan-info="lanInfo" :wan-info="wanInfo" />
            </div>
          </div>
          <div class="col-lg-6 col-md-12 col-sm-12">
            <div class="wrapper no-margin">
              <AlarmMonitoring :lanInfo="lanInfo" :box-id="boxId" :detailInfo="detailInfo" :subDevices="subDevices" @checkDevice="checkDevice" :isOnline="isOnline" :mem-and-rom="memAndRom" :signal="signal" @updateLanSuccess="updateLanSuccess" @closeLan="closeLan"/>
            </div>
          </div>
        </div>
        <div>
          <InfoDetail :box-id="boxId" :subDevices="subDevices" :detailInfo="detailInfo" @operateSuccess="operateSuccess" :isOnline="isOnline"/>
        </div>
      </q-infinite-scroll>
    </q-scroll-area>

  </div>
</template>

<script>
import GatewayDetail from './components/detail-components/gateway-detail'
import LanParams from './components/detail-components/lan-params-old'
import AlarmMonitoring from './components/detail-components/alarm-monitoring'
import InfoDetail from './components/detail-components/info-detail'
import { getBoxInfo, getDeviceCascade, getLanQuery, getWan, onlineStatus, subDevices } from '../../boot/miot/list'
import refreshMixin from '../../assets/js/refresh-mixin'
import { mapGetters } from 'vuex'
import { runningState } from '../../boot/miot/details'
// import _ from 'lodash'

export default {
  name: 'miot-detail',
  mixins: [refreshMixin],
  components: {
    GatewayDetail,
    LanParams,
    AlarmMonitoring,
    InfoDetail
  },
  data () {
    return {
      thumbStyle: this.CommonConfig.thumbStyle,
      boxId: '',
      detailInfo: {
        boxId: '',
        deployedDate: '',
        boxStatus: '',
        onLineStatus: '',
        wanCfg: '',
        wanType: '',
        productSN: '',
        productName: '',
        deviceSN: '',
        hwVersion: '',
        swVersion: '',
        software: '',
        hardware: '',
        lineStatus: '',
        pd: ''
      },
      wanInfo: {
        wan: '',
        wan1: '',
        dns: '',
        dns1: ''
      },
      lanInfo: {
        lan0: {
          dhcp: null,
          gateway: '',
          ipaddr: '',
          netmask: '',
          speed: null
        },
        lan1: {
          dhcp: null,
          gateway: '',
          ipaddr: '',
          netmask: '',
          speed: null
        }
      },
      lanVisible: false,
      subDevices: [],
      deviceCascade: [],
      timer: null,
      memAndRom: {
        memValue: 0,
        romValue: 0,
        memWarning: false,
        romWarning: false
      },
      signal: {
        signalValue: 0,
        is4G: false
      },
      subscribeOptions: [], // 所有订阅的list
      runningStateTimer: null
    }
  },
  watch: {
    boxId: {
      immediate: true,
      handler: function (val) {
        if (val) {
          this.getBoxWan(val)
          this.getBoxInfo(val).then(() => {
            this.getDeviceCascade().then(() => {
              this.getSubDevices(val)
            })
          })
          this.getLanQuery(val)
          // 先获取状态值是否是4G，如果是4G才订阅信号模块
          this.getRunningState(val).then(() => {
            this.initWebSocket(val)
          })
        }
      }
    }
  },
  computed: {
    isOnline () {
      return this.detailInfo.onLineStatus === 'ONLINE'
    },
    ...mapGetters([
      'client'
    ])
  },
  created () {
    const { boxId, deployedDate, boxStatus, wanCfg, onLineStatus } = this.$route.query
    this.boxId = boxId
    this.detailInfo.boxId = boxId
    this.detailInfo.deployedDate = deployedDate
    this.detailInfo.boxStatus = boxStatus
    this.detailInfo.wanCfg = wanCfg
    this.detailInfo.onLineStatus = onLineStatus
    this.getLiveStatus()
  },
  beforeDestroy () {
    this.unsubscribeWebSocket(this.boxId)
    clearInterval(this.timer)
    clearInterval(this.runningStateTimer)
  },
  methods: {
    /**
     * 初始化websocket
     */
    async initWebSocket (boxId) {
      this.$nextTick(() => {
        if (this.client && this.client.connected) {
          this.onMemoryStatus(boxId)
          this.onRomStatus(boxId)
          this.onSignalStatus(boxId)
          this.onDeviceStatus(boxId)
        } else {
          console.log('websocket未连接')
        }
      })
    },

    unsubscribeWebSocket () {
      this.subscribeOptions.forEach(item => {
        item.unsubscribe()
      })
      this.subscribeOptions = []
    },

    /**
     * 内存报警 "data" : {"current":"449146880","total":"518660096","alarmTime":"1598422612"}
     * @param boxId
     */
    onMemoryStatus (boxId) {
      const subscribe = this.client.subscribe(
        `/topic/deviceData/alarmMem/${boxId}`,
        (message) => {
          try {
            const ret = JSON.parse(message.body)
            // 获取当前内存
            const current = ret.data.current
            // 获取总的内存
            const total = ret.data.total
            // 如果都获取到的话
            if (current && total && !isNaN(Number(current)) && !isNaN(Number(total))) {
              this.memAndRom.memValue = Number((Number(current) / Number(total)).toFixed(2))
              this.memAndRom.memWarning = true
            }
          } catch (e) {
            console.log('解析socket内存报警错误' + e)
          }
        }
      )
      this.subscribeOptions.push(subscribe)
    },

    /**
     * 硬盘报警 {"current":"170856448","total":"3757793280","alarmTime":"1598495142"}
     */
    onRomStatus (boxId) {
      const subscribe = this.client.subscribe(
        `/topic/deviceData/alarmRom/${boxId}`,
        (message) => {
          try {
            const ret = JSON.parse(message.body)
            // 获取当前内存
            const current = ret.data.current
            // 获取总的内存
            const total = ret.data.total
            // 如果都获取到的话
            if ((current && total && !isNaN(Number(current)) && !isNaN(Number(total)))) {
              // 计算百分比
              this.memAndRom.romValue = Number((Number(current) / Number(total)).toFixed(2))
              this.memAndRom.romWarning = true
            }
          } catch (e) {
            console.log('解析socket硬盘报警错误' + e)
          }
        }
      )
      this.subscribeOptions.push(subscribe)
    },

    /**
     * 信号强度 {"current":-91,"Time":"1598493253"}
     */
    onSignalStatus (boxId) {
      // 如果不是4G就不订阅这个了
      if (!this.signal.is4G) return
      const subscribe = this.client.subscribe(
        `/topic/deviceData/RSSI4G/${boxId}`,
        (message) => {
          try {
            const ret = JSON.parse(message.body)
            // 获取当前4g信号值
            const current = ret.data.current
            // 如果都获取到的话
            if (current) {
              this.signal.signalValue = this.getSignalValue(current)
            }
          } catch (e) {
            console.log('解析socket硬盘报警错误' + e)
          }
        }
      )
      this.subscribeOptions.push(subscribe)
    },

    /**
     * 根据信号原始值转换为信号强度值
     */
    getSignalValue (value) {
      const data = Number(value)
      if (isNaN(data)) return 0
      if (data > -85) {
        return 5
      } else if (data > -90 && data <= -85) {
        return 4
      } else if (data > -95 && data <= -90) {
        return 3
      } else if (data > -100 && data <= -95) {
        return 2
      } else if (data > -105 && data <= -100) {
        return 1
      }
      return 0
    },

    /**
     * 订阅设备在线状态, 在线 or 离线
     * @param boxId
     */
    onDeviceStatus (boxId) {
      const subscribe = this.client.subscribe(
        `/topic/deviceStatus/update/${boxId}`,
        (message) => {
          try {
            const ret = JSON.parse(message.body)
            // 获取推送的新的状态
            this.detailInfo.onLineStatus = ret.data.status
          } catch (e) {
            console.log('解析socket订阅设备在线状态错误' + e)
          }
        }
      )
      this.subscribeOptions.push(subscribe)
    },
    async getBoxWan (boxId) {
      const { data } = await getWan(boxId)
      if (data) {
        this.wanInfo.wan = data.wan ? data.wan : '--'
        this.wanInfo.wan1 = data.wan1 ? data.wan1 : '--'
        this.wanInfo.dns = data.dns ? data.dns : '--'
        this.wanInfo.dns1 = data.dns1 ? data.dns1 : '--'
      }
    },

    async getLanQuery (boxId) {
      const { data } = await getLanQuery(boxId)
      if (data && data[0]) {
        if (data[0]['lan0']) {
          this.lanInfo.lan0 = data[0]['lan0']
        }
        if (data[0]['lan1']) {
          this.lanInfo.lan1 = data[0]['lan1']
        }
      }
    },

    /**
     * 获取盒子下的子设备
     */
    async getSubDevices (val) {
      const { data } = await subDevices(val)
      if (data && data.length > 0) {
        this.subDevices = data
      } else {
        this.subDevices = []
      }
    },

    async getDeviceCascade () {
      try {
        const { data } = await getDeviceCascade(this.detailInfo.productName)
        if (data && data.children && data.children.length > 0) {
          this.deviceCascade = data.children
        } else {
          this.deviceCascade = []
        }
      } catch (e) {
        this.deviceCascade = []
      }
    },

    async getBoxInfo (boxId) {
      const { data } = await getBoxInfo(boxId)
      if (data) {
        this.detailInfo.productSN = data.productSN ? data.productSN : '--'
        this.detailInfo.productName = data.productName ? data.productName : '--'
        this.detailInfo.deviceSN = data.deviceSN ? data.deviceSN : '--'
        this.detailInfo.hwVersion = data.hwVersion ? data.hwVersion : '--'
        this.detailInfo.swVersion = data.swVersion ? data.swVersion : '--'
        this.detailInfo.software = data.software ? data.software : '--'
        this.detailInfo.hardware = data.hardware ? data.hardware : '--'
        this.detailInfo.lineStatus = data.lineStatus ? data.lineStatus : '--'
        this.detailInfo.pd = data.pd ? data.pd : '--'
      }
    },

    /**
     * 获取当前的状态值
     */
    async getRunningState (boxId) {
      try {
        const { data } = await runningState(boxId)
        // 获取内存信息
        if (data.memInfo) {
          const current = data.memInfo.current
          const total = data.memInfo.total
          if (current && total && !isNaN(Number(current)) && !isNaN(Number(total))) {
            this.memAndRom.memValue = Number((Number(current) / Number(total)).toFixed(2))
            this.memAndRom.memWarning = data.memInfo.flag
          }
        }
        // 获取硬盘信息
        if (data.romInfo) {
          const current = data.romInfo.current
          const total = data.romInfo.total
          if (current && total && !isNaN(Number(current)) && !isNaN(Number(total))) {
            this.memAndRom.romValue = Number((Number(current) / Number(total)).toFixed(2))
            this.memAndRom.romWarning = data.romInfo.flag
          }
        }
        // 获取网络信号信息
        if (data.networkInfo) {
          const current = data.networkInfo.current
          this.signal.is4G = data.networkInfo.flag
          if (data.networkInfo.flag) {
            this.signal.signalValue = this.getSignalValue(current)
          }
        }
      } catch (e) {
        Object.assign(this.signal, this.$options.data().signal)
        Object.assign(this.memAndRom, this.$options.data().memAndRom)
      }
    },

    operateSuccess () {
      // 重新获取子设备
      this.getSubDevices(this.boxId)
    },

    checkDevice () {
      // 先调用一次检查是否为离线
      onlineStatus(this.boxId).then((res) => {
        if (res && res.data.status !== 'ONLINE') {
          this.detailInfo.onLineStatus = res.data.status
          this.$q.loading.show({ message: '网关离线中,请稍后...' })
          this.checkOnline().then(() => {
            this.$q.loading.hide()
            this.detailInfo.onLineStatus = 'ONLINE'
          })
        }
      })
    },

    /**
     * 检查盒子是否在线
     */
    checkOnline () {
      if (!this.boxId) return
      return new Promise((resolve, reject) => {
        if (this.timer) clearInterval(this.timer)
        this.timer = setInterval(() => {
          onlineStatus(this.boxId).then(res => {
            if (res && res.data.status === 'ONLINE') {
              resolve()
              clearInterval(this.timer)
            }
          }).catch(() => {
            reject()
            clearInterval(this.timer)
          })
        }, 5000)
      })
    },
    // 修改LAN成功的时候，重新获取一下lanInfo
    updateLanSuccess () {
      this.getLanQuery(this.boxId)
    },
    // 点击关闭LAN,重新赋值，子组件watch到
    closeLan () {
      this.getLanQuery(this.boxId)
      // this.lanInfo = _.cloneDeep(this.lanInfo)
    },
    // 循环获取报警状态
    getLiveStatus () {
      if (this.runningStateTimer) clearInterval(this.runningStateTimer)
      this.runningStateTimer = setInterval(() => {
        this.getRunningState(this.boxId)
      }, 300000)
    }
  }
}
</script>

<style scoped lang="stylus">
.wrapper
  background #ffffff
  border-radius 6px
  margin-right 24px
  margin-bottom 24px

@media (min-width: 1440px)
  .no-margin
    margin-right 0
@media (max-width: 1440px)
  .md-margin
    margin-right 0
@media (min-width: 1040px) and (max-width: 1440px)
  .l-margin
    margin-right 20px
</style>
